﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

namespace PMS.XCMG.Util
{
    public static partial class Extention
    {
        //public static JsonSerializerOptions DefaultJsonSerializerOptions = new JsonSerializerOptions(JsonSerializerDefaults.Web)
        //{
        //    PropertyNameCaseInsensitive = true,
        //    PropertyNamingPolicy = null,
        //    ReferenceHandler = System.Text.Json.Serialization.ReferenceHandler.Preserve
        //};

        public static JsonSerializerSettings DefaultJsonSetting = new JsonSerializerSettings
        {
            ContractResolver = new DefaultContractResolver(),
            ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
            DateFormatString = "yyyy-MM-dd HH:mm:ss.fff"
        };

        /// <summary>
        /// 序列化
        /// </summary>
        /// <param name="obj">要序列化的实体</param>
        /// <returns></returns>
        public static string ToJson(this object obj)
        {
            //return JsonSerializer.Serialize(obj, DefaultJsonSerializerOptions);
            return JsonConvert.SerializeObject(obj, DefaultJsonSetting);
        }

        /// <summary>
        /// 反序列化
        /// </summary>
        /// <typeparam name="T">返回的实体类型</typeparam>
        /// <param name="json">Json字符串</param>
        /// <returns></returns>
        public static T ToObject<T>(this string json)
        {
            //return JsonSerializer.Deserialize<T>(json, DefaultJsonSerializerOptions);
            return JsonConvert.DeserializeObject<T>(json);
        }
    }
}
